import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Scanner;

public class ClientChat {
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private final Scanner scanner = new Scanner(System.in);
    
    public static void main(String[] args) {
        new ClientChat().startApp();
    }

    private void startApp() {
        try {
            String username = getValidUsername();
            connectToServer(username);
        } catch (Exception e) {
            System.err.println("程序异常终止: " + e.getMessage());
        }
    }

    private String getValidUsername() {
        while (true) {
            System.out.print("请输入用户名: ");
            String input = scanner.nextLine().trim();
            if (!input.isEmpty()) {
                return input;
            }
            System.out.println("用户名不能为空!");
        }
    }

    private void connectToServer(String username) {
        try (Socket socket = new Socket(InetAddress.getLocalHost(), 7778);
             DataOutputStream dos = new DataOutputStream(socket.getOutputStream())) {
            
            performLogin(dos, username);
            startMessageReceiver(socket);
            enterChatLoop(dos);
            
        } catch (IOException e) {
            System.err.println("连接服务器失败: " + e.getMessage());
        }
    }

    private void performLogin(DataOutputStream dos, String username) throws IOException {
        dos.writeInt(1);
        dos.writeUTF(username);
        dos.flush();
        System.out.println("成功登录简易聊天室！");
    }

    private void startMessageReceiver(Socket socket) {
        new Thread(() -> {
            try (var in = new java.io.DataInputStream(socket.getInputStream())) {
                while (true) {
                    System.out.println(in.readUTF());
                }
            } catch (IOException e) {
                System.out.println("与服务器的连接已断开");
                System.exit(0);
            }
        }).start();
    }

    private void enterChatLoop(DataOutputStream dos) {
        while (true) {
            String message = scanner.nextLine().trim();
            if (message.equalsIgnoreCase("/exit")) {
                System.out.println("退出聊天室");
                System.exit(0);
            }
            sendMessage(dos, message);
        }
    }

    private void sendMessage(DataOutputStream dos, String message) {
        if (!message.isEmpty()) {
            try {
                dos.writeInt(2);
                dos.writeUTF(message);
                dos.flush();
                System.out.printf("[你][%s]: %s%n", 
                    DATE_FORMAT.format(System.currentTimeMillis()), message);
            } catch (IOException e) {
                System.err.println("消息发送失败: " + e.getMessage());
            }
        }
    }
}
